import 'package:file_transfer/manager/webrtc_manager.dart';
import 'package:file_transfer/model/message_model.dart';
import 'package:file_transfer/model/simple_model.dart';
import 'package:file_transfer/pojo/message.dart';
import 'package:file_transfer/route/simple_route.dart';
import 'package:file_transfer/theme/colors.dart';
import 'package:file_transfer/widget/client_widget.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ReceiveSharingPage extends StatefulWidget {
  const ReceiveSharingPage({super.key});

  @override
  State<ReceiveSharingPage> createState() => _ReceiveSharingPageState();
}

class _ReceiveSharingPageState extends State<ReceiveSharingPage> {


  _selectClient(SimpleModel simpleModel,MessageModel messageModel,WebrtcManager webrtcManager,User user, VoidCallback back) async{
    messageModel.client = User(key: user.key);
    if(simpleModel.isShareFile) {
      for (final file in simpleModel.shareFileList) {
        webrtcManager.sendFile(file);
      }
    }else{
      webrtcManager.sendChatMessage(simpleModel.shareText);
    }
    debugPrint("文件发送成功");
    simpleModel.setPageToFileTransfer();
    back();
  }


  Widget _other(VoidCallback toLogin){
    final style = TextStyle(
      color: ThemeColors.blue,
      fontSize: 25,
      fontWeight: FontWeight.bold
    );
    return Center(
      child: Consumer<SimpleModel>(
        builder: (BuildContext context, value, Widget? child) {
          return !value.isLogin
              ? GestureDetector(
                  onTap: toLogin,
                  child:  Text("请先登录再进行操作（点我返回登录）", style: style))
              :  Center(
                  child: Text("当前没有在线客户端", style: style),
                );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final messageModel = context.watch<MessageModel>();
    final userList = messageModel.onlineUserList;

    void toLogin(){SimpleRoute.instance().toLoginPage(context);}
    void back(){SimpleRoute.instance().toBack(context);}
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: userList.isNotEmpty ? ListView.builder(
            itemCount: userList.length,
            itemBuilder: (BuildContext context, int index) {
              final simpleModel = context.read<SimpleModel>();
              final user = userList[index];
              final webrtcManager = WebrtcManager.instance(context);
              return GestureDetector(onTap:()=> _selectClient(simpleModel,messageModel,webrtcManager,user,back),
                child: ClientWidget(user.name,key: Key(user.key),selected: user.key == messageModel.client.key),);
            }):_other(toLogin),
      ),
    );
  }
}
